import store from '@/store'
import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { setToken } from '@/utils'
import { generateTitle } from '@/lang/utils'
NProgress.configure({ showSpinner: false })

export default async function bootStrapRouter() {
  if (process.env.NODE_ENV === 'development' || process.env.VUE_APP_TEST_TOKEN) {
    setToken('116-L88TW1LegeXljpUx')
  }

  store.dispatch('app/getUserInfo')
  store.dispatch('app/getCountry')
  store.dispatch('app/getChannel')
  const permMap = await store.dispatch('app/getMenus')
  const accessRoutes = await store.dispatch('router/generateRoutes', null)
  console.log('accessRoutes:', accessRoutes)
  router.addRoutes(accessRoutes)

  if (accessRoutes.length && window.location.pathname === '/') {
    const fristRoute = accessRoutes[0]
    const path = fristRoute?.redirect ?? fristRoute.path
    window.location.replace(`${window.location.protocol}//${window.location.host}${path}`)
  }

  // 跳转路由
  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    document.title = generateTitle(to.meta.title) // 设置标题
    next()
  })

  // 路由后置守卫
  router.afterEach(() => {
    NProgress.done()
  })
}
